//
//  YMComposeViewController.swift
//  YMWeiBo
//
//  Created by mimi on 16/7/26.
//  Copyright © 2016年 mimi. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

var text :String?

class YMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    

        setupUI()
    }

    func setupUI() {
//        textView.scrollEnabled = true
        textView.inputView = emotiocnKeyboardView
        composePictureView.hidden = true
        
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, targe: self, action: #selector(YMComposeViewController.cancelClick))
       navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, targe: self, action: #selector(YMComposeViewController.sendClick))
        navigationItem.rightBarButtonItem?.enabled = false
        
        //add控件
        view.addSubview(textView)
        textView.addSubview(composePictureView)
        view.addSubview(toolBarView)
        textView.placeholder = "shjahkjjkhk"
        text = self.textView.placeholder ?? ""
        
        //约束
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        composePictureView.snp_makeConstraints { (make) in
            make.leading.trailing.equalTo(textView).offset(10)
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.height.equalTo(SCREENW - 20)
        }
        
        toolBarView.snp_makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        toolBarView.closureButton = {(type:YMToolBarViewButtonType) ->()in
            
            switch type {
            case .Picture:
                print("图片")
                self.selecImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                self.switchKeyboard()
            case .Add:
                print("+")
            }
            self.composePictureView.closure = {[weak self] in
                
                self?.selecImage()
                
            }
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YMComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        //删除按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YMComposeViewController.emoticonDeleteButton), name: WBEmoticonDeleteButtonNoti, object: nil)
        
        
        //表情按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YMComposeViewController.emoticonButtons(_:)), name: WBEmoticonButtonsNoti, object: nil)
        
    }
    
    
    //        MARK: - 响应板块
    
    //表情按钮
    func emoticonButtons(noti: NSNotification) {

        // object为空或者不是 YMEmoticon类型 
        
        guard let emoticon = noti.object as? YMEmoticon else{
            return
        }
 
        //判断是否是emoji表情
        if emoticon.isEmoji{
            //十六进制字符串转换格式
            let codeStr = (emoticon.code ?? "" as NSString).emoji()
            //插入
            textView.insertText(codeStr)
        }else{
//            //代表是图片表情
//            //获取当前textView的富文本
//            let allAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            //文本附件
//            let att = NSTextAttachment()
//            //设置image
//            att.image = UIImage.getEmoticonImage(emoticon.path)
//            //计算行高
//            let lineHeight = textView.font!.lineHeight
//            //记住一定要设置bounds
//            att.bounds = CGRectMake(0, -4, lineHeight, lineHeight)
//            
//            //不可变的富文本
//            let attr = NSAttributedString(attachment: att)
//            //获取当前光标的位置
//            let selectedRange = textView.selectedRange
//            
//            //拼接 - 失败
//            //allAttr.appendAttributedString(attr)
//            
//            //插入不可变富文本 - 失败
//            //allAttr.insertAttributedString(attr, atIndex: selectedRange.location)
//            //
//            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
//            
//            allAttr.addAttributes([NSFontAttributeName: textView.font!], range: NSRange(location: 0, length: allAttr.length))
//            //赋值
//            textView.attributedText = allAttr
//            
//            //重新设置textView 的选中光标
//            textView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            // 代表是图片表情
            // 获取当前composeTextView 的富文本
            let allAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            // 文本附件
            let att = NSTextAttachment()
            // 设置image
            att.image = UIImage.getEmoticonImage(emoticon.path)
            // 计算行高
            let lineHeight = textView.font!.lineHeight
            // 记住一定要设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            // 不可变的富文本
            let attr = NSAttributedString(attachment: att)
            // 获取当期选中的光标
            let selectedRange = textView.selectedRange
            // 拼接 - 失败
            //allAttr.appendAttributedString(attr)
            // 插入不可变富文本 - 失败
            // allAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            // 设置富文本属性
            allAttr.addAttributes([NSFontAttributeName: textView.font!], range: NSRange(location: 0, length: allAttr.length))
            // 赋值
            textView.attributedText = allAttr
            // 重新设置composeTextView 选中光标
            textView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
        }
    }
    
    //删除按钮
    func emoticonDeleteButton() {
        textView.deleteBackward()
    }
    
    //取消
    func cancelClick() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发布
    func sendClick() {
        var allText = ""
        //遍历textView.attributedtext
        
        
        textView.attributedText.enumerateAttributesInRange(NSRange(location: 0,length: textView.attributedText.length), options: []) { (result, range, _) in
            
            
            if let att = result["NSAttachment"] as? YMTextAttachment{
               allText += (att.emoticon?.chs ?? "")
            }else{
                
                //文字
                //字符串截取
                let str = (self.textView.attributedText.string as NSString).substringWithRange(range)
                
                allText += str
            }
        }
        
        composePictureView.imageList.count > 0 ? upload(allText):update(allText)
        
        
    }
    
    
    //监听键盘将要改变frame
    func keyboardWillChangeFrame(noti:NSNotification) {
        guard let userInfo = noti.userInfo else{
            return
        }
        //获取时间
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        //获取value frame 并且转换成NSValue 格式
        let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        
        
        //在转化为rect
        
        let rect = value.CGRectValue()
        
        //调换toolbar的地步约束
        self.toolBarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(Double(duration)) {
            self.toolBarView.layoutIfNeeded()
        }
        
    }
    
    //表情按钮
//    func didEmoticonButton() {
//        self.textView.becomeFirstResponder()
//        self.textView.inputView?.reloadInputViews()
//        
//    }
    
    
    
    
    //        MARK: - 懒加载
    
    //keyboardView
    lazy var emotiocnKeyboardView:YMEmotiocnKeyboardView = YMEmotiocnKeyboardView()
    
    
    //textView
    lazy var textView:YMComposeTextView = {
       let view = YMComposeTextView()
        view.font = UIFont.systemFontOfSize(16)
        view.delegate = self
        view.alwaysBounceVertical = true
        return view
    }()
    //collectionView
    lazy var composePictureView:YMComposePictureView = {
            let view = YMComposePictureView()
        return view
    }()
    //toolBarView

    lazy var toolBarView:YMToolBarView = YMToolBarView()


    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}


extension YMComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()

        textView.hasText() ? (self.textView.placeholder = "") : (self.textView.placeholder = text)
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //如果拖动textView取消第一响应
        self.textView.resignFirstResponder()
    }

}


//MARK: -底部视图按钮点击会掉

extension YMComposeViewController{
  //pickerView选中图片处理
    func selecImage() {

       let pickVc = UIImagePickerController()
        
        pickVc.delegate = self
        
        self.presentViewController(pickVc, animated: true, completion: nil)
        
    }
    
    // -切换键盘
    
    func switchKeyboard() {
        
        textView.becomeFirstResponder()
        if textView.inputView == nil{
            //代表是默认键盘
            
            textView.inputView = emotiocnKeyboardView
            toolBarView.isEmoticon = true
            
        }else{
            //代表为自定义表情键盘
            textView.inputView = nil
            toolBarView.isEmoticon = false
        }
        
        //刷新inputView
        textView.reloadInputViews()
        
    }
    
    
}

//MARK: -获取背景磨砂图片
extension YMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePictureView.addImages(image.getImageScale(600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
}

//MARK: 发布微博

extension YMComposeViewController{
    
    //文字微博
    func update(status:String) {
        
        YMNetworkTools.sharedTools.compiseUpdate(status, success: { (response) in
            
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) in
              SVProgressHUD.showErrorWithStatus("发部失败")
        }
        
        
        
    }
    
    
    
    //图片微博
    
    func upload(status:String){
        
        YMNetworkTools.sharedTools.composeUpload(status, imageList: composePictureView.imageList, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) in
            SVProgressHUD.showErrorWithStatus("发部失败")    
        }
        
    }
    
}

